import csv
import os

from django.conf import settings
from django.core.management.base import BaseCommand

from apps.base.models import Department, Rights, Role, User


def dict_to_orm(d, o):
    for k, v in d.items():
        # print(k, v)
        if k == "password":
            o.password = v  # 这里会触发密码加密的逻辑 相当于self.password_hash = md5(password)
        else:
            # 在csv没有值的字段,都传None,则该字段得设置为可为空 没传才会用默认值!传None也是传了呀.
            setattr(o, k, v or None)


def csv_to_databases(path, orm_class):
    with open(path, encoding="utf-8") as file:
        for d in csv.DictReader(file):
            o = orm_class()
            dict_to_orm(d, o)
            o.save()  # 使用Django的save()方法  user表中没有password字段,save时,传了password字段，无碍


class Command(BaseCommand):
    help = '批量初始化rbac的数据!!'

    def handle(self, *args, **options):
        self.stdout.write("开始批量添加数据...")

        # 删除所有数据
        Department.objects.all().delete()
        Rights.objects.all().delete()
        Role.objects.all().delete()
        User.objects.all().delete()

        # 关闭外键约束（适用于 MySQL）
        # with connection.cursor() as cursor:
        #     cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")

        root = settings.BASE_DIR

        # 处理权限数据
        rights_data_path = os.path.join(root, "static", "init_data", "ums_rights.csv")
        csv_to_databases(rights_data_path, Rights)

        # 处理角色数据
        role_data_path = os.path.join(root, "static", "init_data", "ums_role.csv")
        csv_to_databases(role_data_path, Role)

        # 处理角色与权限的关系
        with open(role_data_path, encoding="utf-8") as file:
            for d in csv.DictReader(file):
                role = Role.objects.get(id=d["id"])
                id_list = [int(_id) for _id in d["rights_ids"].split(":")]
                role.rights_list.set(Rights.objects.filter(id__in=id_list))

        # 处理部门数据
        department_data_path = os.path.join(root, "static", "init_data", "ums_department.csv")
        csv_to_databases(department_data_path, Department)

        # 处理用户数据
        user_data_path = os.path.join(root, "static", "init_data", "ums_user.csv")
        csv_to_databases(user_data_path, User)

        # 处理用户与角色的关系
        with open(user_data_path, encoding="utf-8") as file:
            for data in csv.DictReader(file):
                user = User.objects.get(id=data["id"])
                role_ids = [int(_id) for _id in data["role_ids"].split(":")]
                user.role_list.set(Role.objects.filter(id__in=role_ids))  # Assuming a ManyToManyField

        # 重新启用外键约束
        # with connection.cursor() as cursor:
        #     cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")

        self.stdout.write(self.style.SUCCESS('Good，爱卿退下吧! Command executed successfully!'))
